package com.isman.placeslist.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class Util {
	public static byte[] LoadImageFromWebOperations(String url) {
		try {
			InputStream is = (InputStream) new URL(url).getContent();

			Bitmap bmp = BitmapFactory.decodeStream(is);
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
			return stream.toByteArray();
		} catch (Exception e) {
			return null;
		}
	}

	public static Bitmap getBitmap(String url) {
		Bitmap bm = null;
		try {
			URL aURL = new URL(url);
			URLConnection conn = aURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
			bis.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bm;
	}

	public static void getBitmap(final String url, final Activity mActivity,
			final ImageView imageView) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Log.e("TAG Start", Thread.currentThread().getName());
					URL aURL = new URL(url);
					URLConnection conn = aURL.openConnection();
					conn.connect();
					InputStream is = conn.getInputStream();
					BufferedInputStream bis = new BufferedInputStream(is);
					final Bitmap bm = BitmapFactory
							.decodeStream(new FlushedInputStream(is));
					bis.close();
					is.close();
					mActivity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							if (bm != null) {
								imageView.setImageBitmap(bm);
								imageView.setScaleType(ScaleType.FIT_XY);
							}
						}
					});
					Log.e("TAG END", Thread.currentThread().getName());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).run();
	}

	public static class FlushedInputStream extends FilterInputStream {
		public FlushedInputStream(InputStream inputStream) {
			super(inputStream);
		}

		@Override
		public long skip(long n) throws IOException {
			long totalBytesSkipped = 0L;
			while (totalBytesSkipped < n) {
				long bytesSkipped = in.skip(n - totalBytesSkipped);
				if (bytesSkipped == 0L) {
					int b = read();
					if (b < 0) {
						break; // we reached EOF
					} else {
						bytesSkipped = 1; // we read one byte
					}
				}
				totalBytesSkipped += bytesSkipped;
			}
			return totalBytesSkipped;
		}
	}
}
